﻿using System;
using System.Collections.Generic;
using System.Text;

namespace NGE
{
    public class Timer
    {
        #region private members
        private long ticksPerSecond = 0;
        //private long elapsedTime = 0;
        private long baseTime = 0;
        private long conTime = 0;
        private double rSec = 1;
        #endregion
        #region Constructors
        /// <summary>
        /// new
        /// </summary>
        public Timer()
        {
            // Use QueryPerformanceFrequency to get frequency of the timer
            if (!WindowsAPI.QueryPerformanceFrequency(ref ticksPerSecond))
                throw new ApplicationException("Timer: Performance Frequency Unavailable");
            Reset();
            WindowsAPI.QueryPerformanceCounter(ref conTime);
        }
        #endregion
        #region public methods
        /// <summary>
        /// 重置时间相关计数器
        /// </summary>
        public void Reset()
        {
            long time = 0;
            WindowsAPI.QueryPerformanceCounter(ref time);
            baseTime = time;
            //elapsedTime = 0;
        }
        public void Record()
        {
            rSec = getSeconds();
        }
        /// <summary>
        /// 获取当前与最近一次 reset 时间差
        /// </summary>
        /// <returns>The time since last reset.</returns>
        double getSeconds()
        {
            long time = 0;
            WindowsAPI.QueryPerformanceCounter(ref time);
            return (double)(time - baseTime) / (double)ticksPerSecond;
        }
        public double Seconds
        {
            get
            {
                return rSec;
            }
        }
        public double TotalSeconds
        {
            get
            {
                long time = 0;
                WindowsAPI.QueryPerformanceCounter(ref time);
                return (double)(time - conTime) / (double)ticksPerSecond;
            }
        }

        /// <summary>
        /// 获取当前系统的时间 ticks 数
        /// </summary>
        /// <returns>The current time in seconds.</returns>
        public double AbsoluteTime
        {
            get
            {
                long time = 0;
                WindowsAPI.QueryPerformanceCounter(ref time);
                return (double)time / (double)ticksPerSecond;
            }
        }
        ///// <summary>
        ///// 获取此次与上次调用此方法的两次时间差
        ///// </summary>
        ///// <returns>The number of seconds since last call of this function.</returns>
        //public double GetElapsedTime()
        //{
        //    long time = 0;
        //    QueryPerformanceCounter(ref time);
        //    double absoluteTime = (double)(time - elapsedTime) / (double)ticksPerSecond;
        //    elapsedTime = time;
        //    return absoluteTime;
        //}
        #endregion
    }
}
